//
//  HNConsultController.m
//  JHFBaseProject
//
//  Created by 朱传正 on 2016/12/16.
//  Copyright © 2016年 好牛. All rights reserved.
//

#import "HNConsultController.h"
#import "HNDocterMsgCell.h"

@interface HNConsultController ()

@property (nonatomic,strong) NSMutableArray *dataSource;

@end

@implementation HNConsultController

- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 0.5)];
    lineLabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:lineLabel];
    

    [self drawView];
    [self initData];
}

-(void)drawView{
    self.dataSource = [NSMutableArray array];
    self.tableView.bounces = NO;
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}

-(void)initData{
    [self getDoctorMessage:0];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
 
    return _dataSource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
 
    return 60;
 
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *consultDic = [NSDictionary dictionaryWithDictionary:_dataSource[indexPath.row]];
    
    static NSString *CellIdentifier = @"HNDocterMsgCell";
    
    HNDocterMsgCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil]firstObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.cellTime setHidden:YES];
    [cell.cellChoiceImage setHidden:YES];
    
    
    NSString *imageStr = [NSString stringWithFormat:@"%@%@",url_Base,[consultDic objectForKey:@"sellerPhoto"]];
    [cell.cellImage sd_setImageWithURL:[NSURL URLWithString:imageStr] placeholderImage:[UIImage imageNamed:@"D99GN4P63Q4F.png"]];
    
    NSString *sellerNickname = [NSString stringWithFormat:@"%@",[consultDic objectForKey:@"sellerNickname"]];
    NSString *sellerUsername = [NSString stringWithFormat:@"%@",[consultDic objectForKey:@"sellerUsername"]];
    if (![AppConfig isNULL:sellerNickname]) {
        cell.cellTitle.text = sellerNickname;
    }else{
        cell.cellTitle.text = sellerUsername;
    }
    
    cell.cellTaskStr.text = [NSString stringWithFormat:@"%@",[consultDic objectForKey:@"createTime"]];
 
    
    return cell;
}


//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
//定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
//进入编辑模式，按下出现的编辑按钮后,进行删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
          NSDictionary *consultDic = [NSDictionary dictionaryWithDictionary:_dataSource[indexPath.row]];
        
        NSString *historyId = [NSString stringWithFormat:@"%@",[consultDic objectForKey:@"historyId"]];
        [self getDeleteHistoryId:historyId andIndexPath:indexPath];
        
    }
}
//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}


#pragma mark - 获取消息
-(void)getDoctorMessage:(NSInteger)tag{
    
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];


    NSLog(@"param = %@",param);
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_consultHistory_list parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
               [self showHint:@"获取咨询记录列表失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            NSArray * obj = [NSArray arrayWithArray:[data objectForKey:@"obj"]];
            NSLog(@"------obj = %@",obj);

            for (int i = 0; i < obj.count; i ++) {
                NSLog(@"%@",obj[i]);
                
                [self.dataSource addObject:obj[i]];
            }
            
            NSLog(@"===self.docterListSource = %@",self.dataSource);
            
            [self.tableView reloadData];
      
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];

        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取咨询记录列表失败"];

    }];
    
    
}

#pragma mark - 删除消息
-(void)getDeleteHistoryId:(NSString *)historyId andIndexPath:(NSIndexPath *)indexPath{
    
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    [param setObject:historyId forKey:@"historyId"];
    
    NSLog(@"param = %@",param);
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_consultHistory_delete parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取咨询记录列表失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            [self showHint:@"删除成功"];
            
            [_dataSource removeObjectAtIndex:indexPath.row];
            // Delete the row from the data source.
            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取咨询记录列表失败"];
        
    }];
    
    
}


@end
